#include "page1.h"            // 设备领用
#include "ui_page1.h"
#include"checkitems.h"
#include"checkdialog.h"
#include<QSqlQuery>
#include<QSqlError>
#include<QUuid>
#include<QDateTime>
#include<QtDebug>
#include<QMessageBox>
#include"src/mes.h"
#include<QSqlTableModel>
#include<QFileDialog>
#include"saveqrcode.h"
#include<QClipboard>
#include<QMenu>
#include<QCompleter>

Page1::Page1(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Page1)
{
    ui->setupUi(this);
    popMenu=new QMenu(ui->tableView);
    popMenu->addAction("复制",this,SLOT(slot_copyData()));
    connect(ui->tableView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slotContextMenu(QPoint)));

    useDialog=new UseDialog;

    classMap=Mes::getInstance()->getClassMap();     // 初始化导入菜单
    QList<QString> itemList=classMap.keys();
    itemList.push_front("");
    ui->classCombox->addItems(QStringList(itemList));

    QStringList locationList=Mes::getInstance()->getCheckItemList("location","locationIndex");
    ui->stationLine->addItems(locationList);

//    QCompleter *completer=new QCompleter(locationList,this);
//    completer->setMaxVisibleItems(7);
//    ui->stationLine->setCompleter(completer);

    initTableView(QStringList());
}

void Page1::initTableView(QStringList sqlist)
{
    UseTableModel *model=new UseTableModel(this);
    model->setSqlist(sqlist);

    model->setTable("importForm");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setHeaderData(0,Qt::Horizontal,QString("勾选设备"));
    model->setHeaderData(1,Qt::Horizontal,QString("设备编号"));
    model->setHeaderData(2,Qt::Horizontal,QString("设备分类"));
    model->setHeaderData(3,Qt::Horizontal,QString("名称"));
    model->setHeaderData(4,Qt::Horizontal,QString("规格"));
    model->setHeaderData(5,Qt::Horizontal,QString("导入人工号"));
    model->setHeaderData(6,Qt::Horizontal,QString("数量"));
    model->setHeaderData(7,Qt::Horizontal,QString("单价"));
    model->setHeaderData(8,Qt::Horizontal,QString("导入日期"));
    model->setHeaderData(9,Qt::Horizontal,QString("验收状态"));
    model->setHeaderData(10,Qt::Horizontal,QString("资产编号"));
    model->select();
    ui->tableView->setModel(model);
//    ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
//    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);      // 菜单策略
}

void Page1::slot_copyData()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(ui->tableView->model()->index(selectCurrentRow,selectCurrentColumn).data().toString());
}

void Page1::slotContextMenu(QPoint pos)
{
    auto index=ui->tableView->indexAt(pos);
    selectCurrentRow=index.row();
    selectCurrentColumn=index.column();
    if(index.isValid()){
        popMenu->exec(QCursor::pos());
    }
}

Page1::~Page1()
{
    delete ui;
}

void Page1::on_checkBox_stateChanged(int arg1)
{
    if(ui->checkBox->checkState()==Qt::Checked){
        if(useDialog->exec()!=QDialog::Accepted){
            ui->checkBox->setCheckState(Qt::Unchecked);
        }
    }
}

UseTableModel::UseTableModel(QObject *parent, QSqlDatabase db)
{

}

bool UseTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(!index.isValid())
        return false;


    if (role == Qt::CheckStateRole && index.column() == checkColumn)
    {
        check_state_map.clear();
        check_state_map[index.row()] = (value == Qt::Checked ? Qt::Checked : Qt::Unchecked);return true;
    }
    else
        return QSqlTableModel::setData(index, value,role);
}

QVariant UseTableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    if (index.column() != checkColumn )
    {
        return QSqlTableModel::data(index, role);
    }
    switch(role)
    {
        case Qt::CheckStateRole:
        if(index.column() == checkColumn)
        {
            if (check_state_map.contains(index.row()))
            {
//                qDebug()<<"data";
                return Qt::Checked;
//                return check_state_map[index.row()] == Qt::Checked ? Qt::Checked : Qt::Unchecked;
            }

            return Qt::Unchecked;
        }
        default:
            return QVariant();
    }
    return QVariant();
}

Qt::ItemFlags UseTableModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return 0;
    if (index.column() == checkColumn)
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable;
    else
        return QSqlTableModel::flags(index);
    return  Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

QString UseTableModel::selectStatement() const
{
    QString condition="where status='已验收' and account!=0";
    for(QString tmp:sqlist){
        if(tmp==NULL){
            continue;
        }
        condition+=QString(" and ")+tmp;
    }

    QString sql=QString("SELECT TOP 500 [status],[NO] \
            ,[className]    \
            ,[norms]    \
            ,[model]    \
            ,[workNumber]   \
            ,[account]  \
            ,[price]    \
            ,[date] \
            ,[status]   \
            ,[assistCode] \
        FROM [dm-data].[dbo].[importForm] %1").arg(condition);

    qDebug()<<sql;
    return sql;
}

void Page1::on_pushButton_clicked()                     // 查询
{
    QStringList sqlist;
    if(ui->classCombox->currentText().trimmed()!=""){
        sqlist<<QString("className='%1'").arg(ui->classCombox->currentText().trimmed());
    }

//    if(ui->statusComboBox->currentText().trimmed()!=""){
//        sqlist<<ui->statusComboBox->currentText().trimmed();
//    }

    if(ui->normsLine->text().trimmed()!=""){
        sqlist<<QString("norms like '%%1%'").arg(ui->normsLine->text().trimmed());
    }

    if(ui->NOLine->text().trimmed()!=""){
        sqlist<<QString("NO like '%%1%'").arg(ui->NOLine->text().trimmed());
    }

    initTableView(sqlist);
}

void Page1::on_pushButton_2_clicked()           // 刷新
{
    initTableView(QStringList());
}

void Page1::on_pushButton_3_clicked()       // 导出Excel
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File")," ",tr("file (*.csv)"));
    if (!fileName.isEmpty())
    {
        QString textData;
        int rows = ui->tableView->model()->rowCount();
        int columns = ui->tableView->model()->columnCount();
        for(int j=1;j<columns;j++){
            textData+=ui->tableView->model()->headerData(j,Qt::Horizontal,Qt::DisplayRole).toString();
            textData += "," ;
        }
        textData += "\n";
        for(int i = 0; i < rows; i++){
            for(int j = 1; j < columns; j++){
                    textData += ui->tableView->model()->data(ui->tableView->model()->index(i,j)).toString();
                    textData += "," ;     // for .csv file format
            }
            textData += "\n";             // (optional: for new line segmentation)
        }
        // [Save to file] (header file <QFile> needed)
        // .csv
        QFile csvFile(fileName);
        if(csvFile.open(QIODevice::WriteOnly | QIODevice::Truncate)){
            QTextStream out(&csvFile);
            out << textData;
            csvFile.close();
        }
    }
}

void Page1::clearWidget()
{
    ui->useWorkNumber->clear();
    ui->useAccount->setValue(0);
    ui->normsLine->clear();
    ui->checkBox->setCheckState(Qt::Unchecked);
    ui->msgLabel->clear();
    initTableView(QStringList());
}

void Page1::on_pushButton_4_clicked()
{
    if(ui->useAccount->value()<=0){
        ui->msgLabel->setText("领用数量不能为0");
        return;
    }

    if(ui->useWorkNumber->text().trimmed()==""){
        ui->msgLabel->setText("带*号项目不能为空");
        return;
    }

    if(!Mes::getInstance()->workNumberIsExist(ui->useWorkNumber->text().trimmed())){
        ui->msgLabel->setText("该工号不存在");
        return;
    }

    QMap<QString,QVariant> checkMap;
    QMap<QString,QVariant> recheckMap;
    QMap<QString,QVariant> maintainMap;

    if(ui->checkBox->checkState()==Qt::Checked){
        checkMap=useDialog->checkMap;
        recheckMap=useDialog->recheckMap;
        maintainMap=useDialog->maintainMap;
    }

    QStringList tagList;
    UseTableModel *model=dynamic_cast<UseTableModel *>(ui->tableView->model());
    auto i=model->check_state_map.begin();
    QString NOtmp=model->index(i.key(),1,QModelIndex()).data().toString();
    QString classTmp=model->index(i.key(),2,QModelIndex()).data().toString();
    QString normsTmp=model->index(i.key(),3,QModelIndex()).data().toString();
    QString assistCode=model->index(i.key(),10,QModelIndex()).data().toString();
    int accountTmp=ui->useAccount->value();
//    double singePriceTmp=model->index(i.key(),7,QModelIndex()).data().toDouble();

    int sumAccount=model->index(i.key(),6,QModelIndex()).data().toInt();
    int surplusAccount=sumAccount-accountTmp;
    if(surplusAccount<0 || sumAccount==0){
        ui->msgLabel->setText(QString("所选设备数量不足%1个").arg(accountTmp));
        return;
    }

    tagList<<QString("设备编号：%1").arg(NOtmp);
    tagList<<QString("设备分类：%1").arg(classTmp);
    tagList<<QString("设备名称：%1").arg(normsTmp);
    tagList<<QString("资产编号：%1").arg(assistCode==NULL?"无":assistCode);
    tagList<<QString("领用数量：%1").arg(accountTmp);
    tagList<<QString("超期年限：%1").arg(ui->overTime->value()==0?"无":QString("%1个月").arg(ui->overTime->value()));
    tagList<<QString("领用人工号：%1").arg(ui->useWorkNumber->text().trimmed());

    QMap<QString,QVariant> userMap;
    userMap.insert("NO",NOtmp);
    userMap.insert("account",surplusAccount);
    userMap.insert("useAccount",accountTmp);
    userMap.insert("useWorkNumber",ui->useWorkNumber->text().trimmed());
    userMap.insert("agent",Mes::getInstance()->workNumber);
    userMap.insert("overTime",ui->overTime->value());
    userMap.insert("station",ui->stationLine->lineEdit()->text().trimmed());

    if(Mes::getInstance()->insertAndUpdateUserForm(userMap,checkMap,recheckMap,maintainMap)){
        SaveQRCode saveDialog(tagList);
        saveDialog.exec();
        ui->msgLabel->clear();
        initTableView(QStringList());
    }
}

void Page1::on_useWorkNumber_textEdited(const QString &arg1)
{
    QString name;
    if(Mes::getInstance()->getName(arg1,name)){
        ui->nameLabel->setText(name);
    }else{
        ui->nameLabel->setText("工号不存在");
    }
}
